
import 'package:device_info_plus/device_info_plus.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../generated/l10n.dart';

/// 权限工具
enum PermissionType { camera, photo }

class PermissionUtil {
  /// 权限请求
  static Future<bool> requestPermission(PermissionType type) async {
    if (type == PermissionType.camera) {
      //相机权限
      return await requestCamePermission();
    } else if (type == PermissionType.photo) {
      //相册权限
      if (GetPlatform.isAndroid) {
        final androidInfo = await DeviceInfoPlugin().androidInfo;
        if (androidInfo.version.sdkInt <= 32) {
          return await requestStoragePermission();
        } else {
          return await requestPhotosPermission();
        }
      } else if (GetPlatform.isIOS) {
        return await requestPhotosPermission();
      }
      return false;
    }
    //其它权限
    return false;
  }

  /// 请求相机权限
  static Future<bool> requestCamePermission() async {
    PermissionStatus status = await Permission.camera.status;
    if (status.isDenied) {
      // 权限被拒绝
      bool isPermanentlyDenied = await Permission.camera.isPermanentlyDenied;
      if (isPermanentlyDenied) {
        // 权限被标记为“不再询问”，引导用户前往设置页面手动启用权限
        showTipAlert('Permission denied');
        return false;
      } else {
        // 请求权限
        final nStatus = await Permission.camera.request();
        return nStatus.isGranted;
      }
    }
    return status.isGranted;
  }

  /// 安卓请求储存权限
  static Future<bool> requestStoragePermission() async {
    var status = await Permission.storage.status;
    if (status.isDenied) {
      // 权限被拒绝
      bool isPermanentlyDenied = await Permission.storage.isPermanentlyDenied;
      if (isPermanentlyDenied) {
        // 权限被标记为“不再询问”，引导用户前往设置页面手动启用权限
        showTipAlert('Permission denied');
        return false;
      } else {
        // 请求权限
        final nStatus = await Permission.storage.request();
        return nStatus.isGranted;
      }
    }
    return status.isGranted;
  }

  /// 请求相册权限
  static Future<bool> requestPhotosPermission() async {
    var status = await Permission.photos.status;
    if (status.isDenied || status.isLimited) {
      // 权限被拒绝
      bool isPermanentlyDenied = await Permission.photos.isPermanentlyDenied;
      bool isLimited = await Permission.photos.isLimited;
      if (isPermanentlyDenied || isLimited) {
        // 权限被标记为“不再询问”，引导用户前往设置页面手动启用权限

        isPermanentlyDenied
            ? showTipAlert('权限成功没')
            : showTipAlert('权限成功没');
        if (isLimited) {
          return true;
        } else if (isPermanentlyDenied) {
          return false;
        }
      } else {
        // 请求权限
        final nStatus = await Permission.photos.request();
        return nStatus.isGranted;
      }
    }
    return status.isGranted;
  }

  /// 显示提示弹窗
  static showTipAlert(String msg) {
    openAppSettings();
  }
}
